/** @format */

import { computed, ref } from 'vue'
import { GiteeService } from '../services/giteeService'
import { buildDefaultUrl } from '../utils/commonUtils'
import { useCache } from './useCache'

export const useEntity = (options) => {
  const {
    needCache = true,
    cacheTime = -1,
    cacheKey,
    path,
    pathUpdate,
  } = options || {}

  const giteeService = new GiteeService()
  const cache = needCache && useCache<any[]>(cacheKey, cacheTime)
  const data = ref<any>((needCache && cache.getItem()) || {})
  const content = computed(() => data.value?.content || {})
  // 重写fileURL获取逻辑
  let fileURL = ''

  const updateFileUrl = async (params) => {
    if (pathUpdate) {
      fileURL = await pathUpdate(params)
      fileURL = buildDefaultUrl(fileURL)
    }
  }

  const setFileUrl = async () => {
    if (fileURL) return fileURL
    if (typeof path === 'function') {
      fileURL = await path()
    } else {
      fileURL = path
    }
    fileURL = buildDefaultUrl(fileURL)
    return fileURL
  }

  const getData = async (
    params: any = null,
    options: { [key: string]: any } = {}
  ) => {
    // 提供一种更新的path方式
    if (options?.update) {
      await updateFileUrl(params)
    }
    await setFileUrl()
    const res = await giteeService.getFileContentByUrl(fileURL, true)
    data.value = res
    needCache && cache.setItem(res)
  }

  const updateData = async (newData) => {
    const updData = data.value

    updData.content = {
      ...data.value.content,
      ...newData,
    }

    data.value = updData

    await setFileUrl()
    const updateRes = await giteeService.updateFileContentByUrl(
      fileURL,
      updData
    )

    const { sha } = updateRes.data.content || {}
    data.value.sha = sha

    needCache && cache.setItem(data.value)

    return updateRes
  }

  return { data, content, getData, updateData }
}
